package com.lab.widget.image;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;

import com.lab.logtrack.AppLog;


/**
 * Created by ak
 * 图片切矩形圆角
 */
public class RectangleRoundCornerFilter {

    private int mRoundSize;
    private int mWidth;
    private int mHeight;

    public RectangleRoundCornerFilter(int roundSize, int width, int height) {
        this.mRoundSize = roundSize;
        this.mWidth = width;
        this.mHeight = height;
    }

    public Bitmap getFilteredBitmap(Bitmap bitmap) {

        if (null == bitmap || bitmap.isRecycled()) return null;

        try {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float roundPx;
            float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
            roundPx = mRoundSize;

            left = 0;
            top = 0;
            right = width;
            bottom = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = mWidth;
            dst_bottom = mHeight;

            Bitmap result = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(result);

            final Paint paint = new Paint();
            final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
            final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
            final RectF rectF = new RectF(dst);

            paint.setAntiAlias(true);

            canvas.drawARGB(0, 0, 0, 0);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, src, dst, paint);
//            if(bitmap!=result){
//                try {
//                    bitmap.recycle();
//                    bitmap = null;
//                } catch (Exception e) {
//
//                }
//            }
            return result;
        } catch (Exception e) {
            AppLog.w(e.getMessage());
        } catch (OutOfMemoryError e) {
            AppLog.w(e.getMessage());
        }
        return bitmap;

    }


}
